﻿using Furion.Schedule;
using JQData.Core.DbModel;
using JQData.Core.TushareSDK;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.VisualBasic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JQData.Application.Jobs
{
    public class HotMoneyHandle : IJob
    {
        private readonly ILogger<HotMoney> _logger;
        private readonly IConfiguration _configuration;
        private readonly IServiceScopeFactory _scopeFactory;

        public HotMoneyHandle(ILogger<HotMoney> logger
            , IConfiguration configuration
            , IServiceScopeFactory scopeFactory)
        {
            _logger = logger;
            _configuration = configuration;
            _scopeFactory = scopeFactory;
        }

        public async Task ExecuteAsync(JobExecutingContext context, CancellationToken stoppingToken)
        {
            var hotMoneys = await GetHotMoneyList();
            //只有9月1日前的数据
            var date = new DateOnly(2022, 9, 1); //第一次运行完之后 改成3月前就好了

            using var core = new TushareCore("d6bd5319b55741d52682b9586bca1bccd72e9649840c41760fe5eea3");
            var api = new StockApi(core);

            while (true)
            {
                var list = await Get指定日期交易记录(date);

                await 开始统计(list);

                date = date.AddDays(1);


                if (list == null)
                {
                    break;
                }
            }






            throw new NotImplementedException();
        }

        public async Task 开始统计(List<HotMoneyTrade> list)
        {
            using var serviceScope = _scopeFactory.CreateScope();
            var repository = serviceScope.ServiceProvider.GetService<IRepository<HotMoneyStockCycleProfit>>();

            using var core = new TushareCore("d6bd5319b55741d52682b9586bca1bccd72e9649840c41760fe5eea3");
            var api = new StockApi(core);

            foreach (var item in list.OrderBy(i => i.Id))
            {
                var log = await 找到交易日志(repository, item);
                if (log == null)
                {
                    continue;
                }
                var res = await api.GetDailyAsync(item.StockCode, item.Date);
                var dayData = res.FirstOrDefault();

                log.SourceTradeIdList.Add(item.Id);
                log.SourceTradeIds = string.Join(",", log.SourceTradeIdList.Distinct());
                if (item.IsBuy)
                {
                    log.BuyAmount += item.BuyAmount;
                    log.BuyVol += item.BuyAmount / dayData.Low;
                }
                else
                {
                    log.SellAmount += item.SellAmount;
                    log.SellVol += item.SellAmount / dayData.High;
                }

                if (log.SellVol >= log.BuyVol)
                {
                    log.IsWin = log.SellAmount > log.BuyVol;
                    log.EndDate = item.Date;
                    _logger.LogWarning($"游资交易日志已完成，id:{log.Id} 游资：{log.HotMoneyId}，股票：{log.StockId}，开始时间：{log.StartDate}，结束时间：{log.EndDate}");
                }
                await repository.SaveNowAsync();
            }
        }


        public async Task<HotMoneyStockCycleProfit> 找到交易日志(IRepository<HotMoneyStockCycleProfit> db, HotMoneyTrade trade)
        {
            var linq = db.Where(i => i.StockId == trade.StockId)
                         .Where(i => i.HotMoneyId == trade.HotMoneyId)
                         .Where(i => i.StartDate <= trade.Date)
                         .Where(i => i.EndDate == null);
            var log = await linq.FirstOrDefaultAsync();

            if (log != null)
            {
                if (!string.IsNullOrWhiteSpace(log.SourceTradeIds))
                {
                    log.SourceTradeIdList = log.SourceTradeIds.Split(',').Select(i => int.Parse(i)).ToList();
                }
                else
                {
                    log.SourceTradeIdList = new List<int>();
                }



                if (log.SourceTradeIdList.Contains(trade.Id))
                {
                    return null;
                }

                //var buyList = log.SourceBuyTradeIds.Split(',').ToList();
                //var sellList = log.SourceSellTradeIds.Split(',').ToList();
                //log.SourceSellTradeIdList = log.SourceSellTradeIds.Split(',').Select(i => int.Parse(i)).ToList();
                return log;
            }



            if (trade.IsBuy)
            {
                log = new HotMoneyStockCycleProfit()
                {
                    HotMoneyId = trade.HotMoneyId,
                    StockId = trade.StockId,
                    BuyVol = 0,
                    SellVol = 0,
                    BuyAmount = 0,
                    SellAmount = 0,
                    Profit = 0,
                    IsWin = false,
                    HoldingDays = 0,
                    SourceTradeIds = string.Empty,
                    SourceTradeIdList = new List<int>(),
                    HotmoneyName = trade.HmName,
                    StockName = trade.StockName,
                    StartDate = trade.Date,
                    EndDate = null,
                    CreatedTime = DateTime.Now,
                    UpdatedTime = DateTime.Now,
                };
                await db.InsertNowAsync(log);
                return log;
            }
            return null;
        }



        public async Task<List<HotMoneyTrade>> Get指定日期交易记录(DateOnly date)
        {
            using var serviceScope = _scopeFactory.CreateScope();
            var repository = serviceScope.ServiceProvider.GetService<IRepository<HotMoneyTrade>>();
            var list = await repository.Where(i => i.Date == date).ToListAsync();
            return list;
        }


        public async Task<List<HotMoney>> GetHotMoneyList()
        {

            using var serviceScope = _scopeFactory.CreateScope();
            var repository = serviceScope.ServiceProvider.GetService<IRepository<HotMoney>>();
            var list = await repository.Entities.ToListAsync();
            return list;
        }

    }
}
